import axios from 'axios'
import { message as Msg } from 'ant-design-vue'
import useToken from '@/stores/token'
import router from '@/router'

const service = axios.create({
    baseURL: '/api',
    timeout: 50000
})
service.interceptors.request.use(config => {
    const { token } = useToken()
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, error => Promise.reject(error))
service.interceptors.response.use(response => {
    const { success, message, data } = response.data
    if (success) {
        return data
    }
    Msg.error(message)
    return Promise.reject(new Error(message))
}, error => {
    if (error.response && error.response.data && error.response.data.code === 10002) {
        const { removeToken } = useToken()
        removeToken()
        router.push("/login")

    }
    return Promise.reject(error)
})
export default service